﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FQY.Infrastructure.Core
{
    public class EnumHelper
    {
        public sealed class DescriptionAttribute : Attribute
        {
            private string description;
            /// <summary>
            /// 
            /// </summary>
            public string Description { get { return description; } }

            public DescriptionAttribute(string description)
                : base()
            {
                this.description = description;
            }
        }
        /// <summary>
        /// 获取枚举项的描述
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetAttributeDescription(Enum value)
        {
            if (value == null)
            {
                throw new ArgumentException("value");
            }
            string description = value.ToString();
            var fieldInfo = value.GetType().GetField(description);
            var attributes =
                (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes != null && attributes.Length > 0)
            {
                description = attributes[0].Description;
            }
            return description;
        }

        /// <summary>
        /// 验证描述是否在枚举中
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public static bool ValidataAttributeDescription(Type enumType, string description)
        {
            bool result = false;

            foreach (Enum item in Enum.GetValues(enumType))
            {
                if (GetAttributeDescription(item).Equals(description))
                {
                    result = true;
                    break;
                }
            }
            return result;
        }


        /// <summary>
        /// 根据属性获取枚举名称
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public static string GetNameByDescription(Type enumType, string description)
        {
            string result = string.Empty;
            foreach (Enum item in Enum.GetValues(enumType))
            {
                if (GetAttributeDescription(item).Equals(description))
                {
                    result = item.GetSafeString();
                    break;
                }
            }
            return result;
        }

    }
}
